class StoreController < ApplicationController
  before_filter :find_cart, :except => :empty_cart
  skip_before_filter :verify_authenticity_token
  
  def index
    @products = Product.find_products_for_sale
  end  
  
  def add_to_cart
     product = Product.find(params[:id])
     @current_item = @cart.add_product(product)
     respond_to do |format|
       format.js if request.xhr?
       format.html {redirect_to_index}
     end
   rescue ActiveRecord::RecordNotFound
     logger.error("Attempt to access invalid product #{params[:id]}")
       redirect_to_index("Invalid Product")
   end
  
   def empty_cart
     session[:cart] = nil
     redirect_to_index unless request.xhr?
   end
   
   def remove_from_cart
     begin
       product = Product.find(params[:id])
     rescue ActiveRecord::RecordNotFound
       logger.error("Attempt to access invalid product #{params[:id]}")
       redirect_to_index("Invalid Product")
     else
       @current_item = @cart.remove_product(product)
       respond_to do |format|
         format.js if request.xhr?
         format.html {redirect_to_index}
       end
     end
   end
   
   def remove_all
     begin
       product = Product.find(params[:id])
     rescue ActiveRecord::RecordNotFound
       logger.error("Attempt to access invalid product #{params[:id]}")
       redirect_to_index("Invalid Product")
     else
       @current_item = @cart.remove_all_items(product)
       respond_to do |format|
          format.js if request.xhr?
          format.html {redirect_to_index}
       end
     end
   end
   
   def checkout
     @order = Order.new
   end
   
   def save_order
     @order = Order.new(params[:order])
     @order.add_line_items_from_cart(@cart)
     if @order.save
       session[:cart] = nil
       redirect_to_index("Thank You For Your Order")
     else 
       render :action => 'checkout'
     end
   end
   
   def ask
   end  
   
private
  
  def redirect_to_index(msg = nil)
    flash[:notice] = msg
    redirect_to :action => 'index'
  end
  
  def find_cart
    @cart = (session[:cart] ||= Cart.new)
  end
  
protected
  
  def authorize
  end
  
end
